package org.yaac.server.egql.evaluator.aggregator;

import java.math.BigDecimal;
import java.math.RoundingMode;

import org.yaac.server.egql.evaluator.EvaluationResult;

/**
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
public class AvgAggregator implements Aggregator {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private CountAggregator counter;
	
	private SumAggregator sumer;
	
	/**
	 * 
	 */
	public AvgAggregator() {
		counter = new CountAggregator();
		sumer = new SumAggregator();
	}
	
	@Override
	public void aggregate(EvaluationResult delta) {
		counter.aggregate(delta);
		sumer.aggregate(delta);
	}
	
	@Override
	public String asString() {
		return getResult().toString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((counter == null) ? 0 : counter.hashCode());
		result = prime * result + ((sumer == null) ? 0 : sumer.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AvgAggregator other = (AvgAggregator) obj;
		if (counter == null) {
			if (other.counter != null)
				return false;
		} else if (!counter.equals(other.counter))
			return false;
		if (sumer == null) {
			if (other.sumer != null)
				return false;
		} else if (!sumer.equals(other.sumer))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "AvgAggregator [counter=" + counter + ", sumer=" + sumer + "]";
	}

	@Override
	public BigDecimal getResult() {
		// make scale configurable by users?
		BigDecimal avg = sumer.getResult().divide(counter.getResult(), 10, RoundingMode.HALF_UP);
		return avg;
	}
}
